package cn.tedu.epidemic.webapi.config;

import cn.tedu.community.commons.restful.JsonResult;
import cn.tedu.community.commons.restful.ServiceCode;
import cn.tedu.epidemic.webapi.filter.JwtAuthorizationFilter;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Autowired
    private JwtAuthorizationFilter jwtAuthorizationFilter;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.exceptionHandling().authenticationEntryPoint(new AuthenticationEntryPoint() {
            @Override
            public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
                String message = "未检测到登录，请登录！（在开发阶段，看到此提示时，请检查客户端是否携带了JWT向服务器端发起请求）";
                JsonResult<Void> jsonResult = JsonResult.fail(ServiceCode.ERR_UNAUTHORIZED, message);
                response.setContentType("application/json; charset=utf-8");
                PrintWriter printWriter = response.getWriter();
                printWriter.println(JSON.toJSONString(jsonResult));
                printWriter.close();
            }
        });
        //调用formLogin()表示启用登录表单页和登出页，如果未调用此方法，则没有登录表单页和登出页
        //http.formLogin();
        //禁用"防止伪造的跨域攻击"
        http.csrf().disable();
        String[] urls = {
                "/doc.html",
                "/**/*.js",
                "/**/*.css",
                "/swagger-resources",
                "/v2/api-docs",
                "/user/login",
                "/user/reg",
                "/user/upload",
                "/user/forgotPass",
                "/user/countPhone/{userPhone:[0-9]+}",
                "/forum/page/{page:[0-9]+}/{pageSize:[0-9]+}",
                "/forum/{isLogin}/{id:[0-9]+}/select",
                "/comment/{forumId:[0-9]+}/{page:[0-9]+}/{pageSize:[0-9]+}/page",
                "/notice/{page:[0-9]+}/{pageSize:[0-9]+}/userNoticeList",
                "/notice/{id:[0-9]+}/UserNoticeStandard",
                "/slideshow/list",
        };
        http.cors();
        http.addFilterBefore(jwtAuthorizationFilter, UsernamePasswordAuthenticationFilter.class);
        //配置url的访问控制
        http.authorizeRequests()//配置url的访问控制
                .mvcMatchers(urls)//匹配某些url
                .permitAll() //直接许可，即：不需要通过认证就可以直接访问
                .anyRequest() //任何请求(基于第一匹配原则)
                .authenticated();//以上配置的请求是通过认证的
    }
}
